<?php
/**
 * Created by PhpStorm.
 * User: fengdh
 * Date: 2019/8/20
 * Time: 15:58
 */

namespace business\company\services;

use business\base\services\DictionaryService;
use business\company\models\DeveloperModel;
use business\user\models\UserIdentityModel;
use common\utils\PinyinUtil;

class DeveloperService
{
    public function getDeveloperIdsList($time = null, $is_valid = false)
    {
        $query = DeveloperModel::find()->select(['developer_id']);
        $time && $query->andWhere('last_modified_time >= :time', [':time' => $time]);
        $is_valid && $query->where(['state' => 2]);
        $data = $query->column();
        return $data;
    }

    /**
     * 根据开发商Id获取该开发商详细的基础信息
     * @param $developerId
     * @return array
     */
    public function getDeveloperBasicInfo($developerId)
    {
        /** @var DeveloperModel $developer */
        $developer = DeveloperModel::findOne($developerId);

        $basicInfo = [];
        $basicInfo['developerId'] = $developerId;
        $basicInfo['developerName'] = !empty($developer) ? htmlspecialchars($developer->company_name) : '';
        $basicInfo['developerLevel'] = !empty($developer) ? $developer->developer_level : '';
        $basicInfo['memberLevel'] = !empty($developer) ? $developer->member_level : '';
        $basicInfo['shortName'] = !empty($developer) ? $developer->short_name : '';
        $basicInfo['namePinyin'] = !empty($developer) ? $this->getPinyin($developer->company_name) : '';
        $basicInfo['companyLogo'] = !empty($developer) ? $developer->company_logo : '';
        $basicInfo['regCityCode'] = !empty($developer) ? $developer->reg_city_code : '';
        $basicInfo['regProvinceCode'] = !empty($developer) ? $developer->reg_province_code : '';
        $basicInfo['regAddress'] = !empty($developer) ? $developer->reg_address : '';
        $basicInfo['state'] = !empty($developer) ? $developer->state : '2';
        $basicInfo['isIPO'] = !empty($developer) ? $developer->is_ipo : 0;
        $basicInfo['enterpriseNature'] = !empty($developer) ? $developer->enterprise_nature : 0;
        //获取省市名称
        $dictionaryService = new DictionaryService();
        $basicInfo['regCityName'] = !empty($basicInfo['regCityCode']) ?
            $dictionaryService->getAreaNameByCodes($basicInfo['regCityCode']) : '';
        $basicInfo['regProvinceName'] = !empty($basicInfo['regProvinceCode']) ?
            $dictionaryService->getAreaNameByCodes($basicInfo['regProvinceCode']) : '';
        $basicInfo['authorize'] = $this->getIsContract($developerId);
        //获取地址全称
        $basicInfo['regLocation'] = '无';
        if (!empty($basicInfo['regCityName']) && !empty($basicInfo['regProvinceName'])) {
            if ($basicInfo['regCityName'] == $basicInfo['regProvinceName']) {
                $basicInfo['regLocation'] = $basicInfo['regProvinceName'] . '市' . $developer->reg_address;
            } else {
                $basicInfo['regLocation'] = $basicInfo['regProvinceName'] . '省' . $basicInfo['regCityName'] . '市' . $developer->reg_address;
            }
        }
        $basicInfo['lastActivityTime'] = $this->getDeveloperLastActivityTime($developerId);
        $basicInfo['developerType'] = !empty($developer) ? $developer->developer_type : '';
        return $basicInfo;
    }

    /**
     * 根据开发商id获取该开发商的统计信息
     * @param $developerId
     * @return array
     */
    public function getDeveloperStatisticInfo($developerId)
    {
        $statistics = [];

        //获取正在招标总数
        $biddingCount = $this->getDeveloperPublishBiddingCount($developerId, null);
        $statistics['biddingCount'] = !empty($biddingCount) ? (int)$biddingCount : 0;

        // 获取正在招标中的总数
        $biddingInProgressCount = $this->getDeveloperPublishBiddingCount($developerId, 2);
        $statistics['biddingInProgressCount'] = !empty($biddingInProgressCount) ? (int)$biddingInProgressCount : 0;

        //获取历史招标数量
        $biddingHistoryCount = $this->getDeveloperPublishBiddingCount($developerId, [2, 3, 5, 10, 15]);
        $statistics['biddingHistoryCount'] = !empty($biddingHistoryCount) ? $biddingHistoryCount : 0;

        //获取正在招募的总数
        $recruitCount = $this->getDeveloperPublishRecruitCount($developerId, true);
        $statistics['recruitCount'] = !empty($recruitCount) ? (int)$recruitCount : 0;

        // 获取正在招募中的总数
        $recruitInProgressCount = $this->getDeveloperPublishRecruitCount($developerId);
        $statistics['recruitInProgressCount'] = !empty($recruitInProgressCount) ? (int)$recruitInProgressCount : 0;

        //获取历史招募的总数
        $recruitHistoryCount = $this->getDeveloperPublishRecruitCount($developerId, true);
        $statistics['recruitHistoryCount'] = !empty($recruitHistoryCount) ? $recruitHistoryCount : 0;

        //获取正在招标招募的总数
        $statistics['procurementCount'] = $statistics['biddingCount'] + $statistics['recruitCount'];

        //获取正在招标招募中的总数
        $statistics['procurementInProgressCount'] = $statistics['biddingInProgressCount'] + $statistics['recruitInProgressCount'];

        //获取历史招标招募的总数
        $statistics['procurementHistoryCount'] = $statistics['biddingHistoryCount'] + $statistics['recruitHistoryCount'];
        return $statistics;
    }

    /**
     * 获取开发商项目信息
     * @param $developerId
     * @return array
     */
    public function getDeveloperProjectsInfo($developerId)
    {
        $sql = <<<sql
            SELECT
                p.uid as id,
                p.name,
                p.province,
                p.city,
                p.status
            FROM
                b2b_bidding.bid_project_manage p
            LEFT JOIN
                b2b_bidding.bid_sub_company sc ON p.sub_company_id = sc.uid AND p.company_id = sc.company_id
            WHERE
                p.company_id = :companyId AND p.is_delete = 0
            ORDER BY p.name
sql;
        $sqlParams[':companyId'] = $developerId;
        $projects = \Yii::$app->db->createCommand($sql, $sqlParams)->queryAll();

        $info = ['projectInfo' => [], 'projectCount' => 0, 'ongoingProjectCount' => 0];
        $projectInfo = [];
        if (!empty($projects)) {
            $dictionaryService = new DictionaryService();
            foreach ($projects as $project) {
                if ($project['status'] == 0) {
                    $info['ongoingProjectCount']++;
                }
                $projectName = $project['name'];
                $cityName = $dictionaryService->getAreaNameByCodes($project['city']);
                array_push($projectInfo, $projectName . (!empty($cityName) ? "($cityName)" : ''));
            }
            $info['projectInfo'] = is_array($projectInfo) ? implode('、', $projectInfo) : $projectInfo;
            $info['projectCount'] = sizeof($projects);
        }

        return $info;
    }

    /**
     * 判断某开发商是否签约
     * @param $developerId
     * @return bool
     */
    private function getIsContract($developerId)
    {
        $sql = <<<sql
            SELECT
                is_contract
            FROM
                b2b_user.uuc_company_contract
            WHERE
                company_id = :companyId
sql;
        $sqlParams = [':companyId' => $developerId];
        $isContract = \Yii::$app->db->createCommand($sql, $sqlParams)->queryScalar();

        if (!empty($isContract) && $isContract == 1) {
            return true;
        }
        return false;
    }

    /**
     * 获取指定字符串的全拼和简拼
     * @param $word
     * @return array
     */
    private function getPinyin($word)
    {
        $pinyin = PinyinUtil::getPinyin($word);
        $shortPinyin = PinyinUtil::getShortPinyin($word);
        return [$pinyin, $shortPinyin];
    }

    /**
     * 获取开发商最后活动时间
     * @param $developerId
     * @return integer
     */
    public function getDeveloperLastActivityTime($developerId){
        $sql = <<<sql
            SELECT
                last_login_time
            FROM
                b2b_user.`uuc_user`
            WHERE
                user_id IN (
                    SELECT
                        user_id
                    FROM
                        b2b_user.`uuc_user_identity`
                    WHERE
                        company_id = :developerId
                )
            ORDER BY
                last_login_time DESC
            LIMIT 1;
sql;
        $sqlParams = [':developerId' => $developerId];
        return intval(strtotime(\Yii::$app->db->createCommand($sql, $sqlParams)->queryScalar()));
    }

    /**
     * 开发商统计招标总数
     * @param $developerId
     * @param $state
     * @return false|null|string
     */
    private function getDeveloperPublishBiddingCount($developerId, $state)
    {
        $sql = <<<sql
            SELECT
                COUNT(ta.uid)
            FROM
                b2b_bidding.bid_announcements ta
            WHERE
                ta.is_delete = 0 AND ta.is_valid =1 AND ta.is_publish_show = 1 AND
                ta.developer_uid = :developerId
sql;
        $sqlParams = [':developerId' => $developerId];

        if (!empty($state) && $state == 2) {
            $sql = $sql . ' AND ta.state =:state';
            $sqlParams[':state'] = $state;
        }
        if (!empty($state) && count($state) > 0 && is_array($state)) {
            $sql = $sql . ' AND find_in_set(ta.state,:state)';
            $sqlParams[':state'] = implode(',', $state);
        }

        return $query = \Yii::$app->db->createCommand($sql, $sqlParams)->queryScalar();
    }

    /**
     * 开发商发布招募数量统计
     * @param $developerId
     * @return false|null|string
     */
    private function getDeveloperPublishRecruitCount($developerId, $isHistory = false)
    {
        $sql = <<<sql
            SELECT
                COUNT(DISTINCT tm.item_id)
            FROM
                b2b_bidding.bid_recruit_item tm
            LEFT JOIN
                b2b_bidding.bid_recruit_item_register trr ON tm.item_id = trr.item_id
            LEFT JOIN
                b2b_company.uuc_developer td ON tm.company_id = td.developer_id
            WHERE
                tm.state = 1 AND tm.company_id = :companyId
sql;
        if ($isHistory === false) {
            $sql .= ' AND tm.register_end_date > NOW()';
        }
        $sqlParams = [':companyId' => $developerId];
        return $query = \Yii::$app->db->createCommand($sql, $sqlParams)->queryScalar();
    }


}